package com.kakarote.examine.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.entity.SimpleUser;
import com.kakarote.core.feign.admin.service.AdminService;
import com.kakarote.core.feign.examine.entity.*;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.examine.constant.*;
import com.kakarote.examine.entity.BO.ExaminePassBO;
import com.kakarote.examine.entity.PO.ExamineRecordLog;
import com.kakarote.examine.entity.PO.*;
import com.kakarote.examine.mapper.ExamineAdvancedConfigMapper;
import com.kakarote.examine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批高级配置表 服务实现类
 * </p>
 *
 * @author zyl
 * @since 2022-08-30
 */
@Service
public class ExamineAdvancedConfigServiceImpl extends BaseServiceImpl<ExamineAdvancedConfigMapper, ExamineAdvancedConfig> implements IExamineAdvancedConfigService {

    @Autowired
    private IExamineAdvancedConfigLimitTimeService advancedConfigLimitTimeService;

    @Autowired
    private IExamineAdvancedConfigLimitTimeUsersService advancedConfigLimitTimeUsersService;

    @Autowired
    private IExamineRecordService examineRecordService;

    @Autowired
    private IExamineRecordLogService examineRecordLogService;

    @Autowired
    private IExamineFlowFinalService examineFlowFinalService;

    @Autowired
    private IExamineRecordLimitService examineRecordLimitService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private IExamineFlowAuthFieldService authFieldService;


    /**
     * 新增或修改高级配置
     *
     * @param examineId               审批id
     * @param batchId                 审批批次id
     * @param examineAdvancedConfigBO 高级配置对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addExamineAdvanceConfig(Long examineId, String batchId, ExamineAdvancedConfigBO examineAdvancedConfigBO) {
        if (ObjectUtil.isEmpty(examineAdvancedConfigBO)) {
            return;
        }
        ExamineAdvancedConfig examineAdvancedConfig = new ExamineAdvancedConfig();
        BeanUtil.copyProperties(examineAdvancedConfigBO, examineAdvancedConfig, "nodeHandleUser", "modifyPermissionType");

        if (ObjectUtil.isNotEmpty(examineAdvancedConfig.getNodeHandleType()) && NodeHandleTypeEnum.FORWARD_OTHERS.getType().equals(examineAdvancedConfig.getNodeHandleType()) && CollectionUtil.isEmpty(examineAdvancedConfigBO.getNodeHandleUser())) {
            throw new CrmException(ExamineCodeEnum.EXAMINE_SET_FLOW_ADWANCE_CONFIG_NODEHANDLE_ERROR);
        }
        if (CollectionUtil.isNotEmpty(examineAdvancedConfigBO.getNodeHandleUser())) {
            String nodeHandleUserStr = examineAdvancedConfigBO.getNodeHandleUser().stream().map(String::valueOf).collect(Collectors.joining(","));
            examineAdvancedConfig.setNodeHandleUser(nodeHandleUserStr);
        }

        List<Integer> modifyPermissionType = examineAdvancedConfigBO.getModifyPermissionType();
        if (CollectionUtil.isNotEmpty(modifyPermissionType)) {
            List<String> modifyPermissionTypeList = modifyPermissionType.stream().map(String::valueOf).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(modifyPermissionTypeList)) {
                String modifyPermissionTypeOfStr = String.join(",", modifyPermissionTypeList);
                examineAdvancedConfig.setModifyPermissionType(modifyPermissionTypeOfStr);
            }
        } else {
            examineAdvancedConfig.setModifyPermissionType("0");
        }
        examineAdvancedConfig.setExamineId(examineId);
        examineAdvancedConfig.setBatchId(batchId);
        examineAdvancedConfig.setAdvancedConfigId(null);
        examineAdvancedConfig.setCreateTime(new Date());
        examineAdvancedConfig.setCreateUserId(UserUtil.getUserId());
        examineAdvancedConfig.setUpdateUserId(UserUtil.getUserId());
        save(examineAdvancedConfig);

        if (ObjectUtil.isNotEmpty(examineAdvancedConfigBO.getLimitTimeStatus()) && examineAdvancedConfigBO.getLimitTimeStatus().equals(1)) {
            ExamineAdvancedConfigLimitTimeBO advancedLimitTimeBO = examineAdvancedConfigBO.getAdvancedLimitTimeBO();
            //添加校验
            if (ObjectUtil.isEmpty(advancedLimitTimeBO.getLimitTime()) || ObjectUtil.isEmpty(advancedLimitTimeBO.getLimitTimeUnit())) {
                throw new CrmException(ExamineCodeEnum.EXAMINE_SET_FLOW_ADWANCE_CONFIG_TIME_ERROR);
            }

            ExamineAdvancedConfigLimitTime examineAdvancedLimitTime = new ExamineAdvancedConfigLimitTime();
            BeanUtil.copyProperties(advancedLimitTimeBO, examineAdvancedLimitTime);
            examineAdvancedLimitTime.setAdvancedConfigId(examineAdvancedConfig.getAdvancedConfigId());
            examineAdvancedLimitTime.setBatchId(batchId);
            examineAdvancedLimitTime.setExamineId(examineId);
            examineAdvancedLimitTime.setCreateUserId(UserUtil.getUserId());
            examineAdvancedLimitTime.setUpdateUserId(UserUtil.getUserId());
            examineAdvancedLimitTime.setCreateTime(new Date());
            examineAdvancedLimitTime.setLimitTimeHandleId(null);
            advancedConfigLimitTimeService.save(examineAdvancedLimitTime);

            List<ExamineAdvancedConfigLimitTimeUsers> examineAdvancedConfigLimitTimeUsersList = new ArrayList<>();
            int sort = 1;
            if (ObjectUtil.isNotEmpty(advancedLimitTimeBO.getHandleUserList())) {
                List<Long> handleUserList = advancedLimitTimeBO.getHandleUserList();
                for (int i = 0; i < handleUserList.size(); i++) {
                    ExamineAdvancedConfigLimitTimeUsers examineAdvancedConfigLimitTimeUsers = new ExamineAdvancedConfigLimitTimeUsers();
                    examineAdvancedConfigLimitTimeUsers.setBatchId(batchId);
                    examineAdvancedConfigLimitTimeUsers.setSort(sort);
                    examineAdvancedConfigLimitTimeUsers.setLimitTimeId(examineAdvancedLimitTime.getLimitTimeHandleId());
                    examineAdvancedConfigLimitTimeUsers.setUserId(handleUserList.get(i));
                    examineAdvancedConfigLimitTimeUsers.setHandleId(null);
                    examineAdvancedConfigLimitTimeUsers.setType(0);
                    examineAdvancedConfigLimitTimeUsersList.add(examineAdvancedConfigLimitTimeUsers);
                    sort++;
                }
            }
            List<Integer> nodeHandleParentLevel = advancedLimitTimeBO.getNodeHandleParentLevel();
            if (CollectionUtil.isNotEmpty(nodeHandleParentLevel)) {
                for (int i = 0; i < nodeHandleParentLevel.size(); i++) {
                    ExamineAdvancedConfigLimitTimeUsers examineAdvancedConfigLimitTimeUsers = new ExamineAdvancedConfigLimitTimeUsers();
                    examineAdvancedConfigLimitTimeUsers.setBatchId(batchId);
                    examineAdvancedConfigLimitTimeUsers.setSort(sort);
                    examineAdvancedConfigLimitTimeUsers.setLimitTimeId(examineAdvancedLimitTime.getLimitTimeHandleId());
                    examineAdvancedConfigLimitTimeUsers.setParentLevel(nodeHandleParentLevel.get(i));
                    examineAdvancedConfigLimitTimeUsers.setHandleId(null);
                    examineAdvancedConfigLimitTimeUsers.setType(1);
                    examineAdvancedConfigLimitTimeUsersList.add(examineAdvancedConfigLimitTimeUsers);
                    sort++;

                }
            }

            List<Long> nodeHandleRole = advancedLimitTimeBO.getNodeHandleRole();
            if (CollectionUtil.isNotEmpty(nodeHandleRole)) {
                for (int i = 0; i < nodeHandleRole.size(); i++) {
                    ExamineAdvancedConfigLimitTimeUsers examineAdvancedConfigLimitTimeUsers = new ExamineAdvancedConfigLimitTimeUsers();
                    examineAdvancedConfigLimitTimeUsers.setBatchId(batchId);
                    examineAdvancedConfigLimitTimeUsers.setSort(sort);
                    examineAdvancedConfigLimitTimeUsers.setLimitTimeId(examineAdvancedLimitTime.getLimitTimeHandleId());
                    examineAdvancedConfigLimitTimeUsers.setRoleId(nodeHandleRole.get(i));
                    examineAdvancedConfigLimitTimeUsers.setHandleId(null);
                    examineAdvancedConfigLimitTimeUsers.setType(2);
                    examineAdvancedConfigLimitTimeUsersList.add(examineAdvancedConfigLimitTimeUsers);
                    sort++;
                }
            }
            advancedConfigLimitTimeUsersService.saveBatch(examineAdvancedConfigLimitTimeUsersList);

        }
    }

    /**
     * 查询高级配置通过批次id
     *
     * @param batchId 批次id
     * @return 高级配置对象
     */
    @Override
    public ExamineAdvancedConfigVO queryAdvancedConfig(String batchId) {
        ExamineAdvancedConfig examineAdvancedConfig = lambdaQuery().eq(ExamineAdvancedConfig::getBatchId, batchId).one();
        return setDefaultValue(examineAdvancedConfig, true);
    }


    /**
     * 查询高级配置通过审批id
     *
     * @param examineId 审批id
     * @return 高级配置对象
     */
    @Override
    public ExamineAdvancedConfigVO queryAdvancedConfigByExamineId(Long examineId) {
        ExamineAdvancedConfig examineAdvancedConfig = lambdaQuery().eq(ExamineAdvancedConfig::getExamineId, examineId).one();
        return setDefaultValue(examineAdvancedConfig, false);
    }

    /**
     * 处理审批日志记录无有效审核人的问题
     *
     * @param recordLogList    审核日志列表
     * @param examineFlowFinal 最终审批流程
     * @param init             是否初始化
     * @return 审核状态
     */
    @Override
    public Integer handleRecordLogByAdvancedConfig(List<ExamineRecordLog> recordLogList, ExamineFlowFinal examineFlowFinal, Boolean init, Object data) {
        ExamineAdvancedConfigVO examineAdvancedConfigVO = queryAdvancedConfigByExamineId(examineFlowFinal.getExamineId());
        return handleRecordLogByAdvancedConfig(recordLogList, examineFlowFinal, init, examineAdvancedConfigVO, null, data);
    }


    /**
     * 处理审批日志记录无有效审核人的问题
     *
     * @param recordLogList           审核日志列表
     * @param examineFlowFinal        最终审批流程
     * @param init                    是否初始化
     * @param examineAdvancedConfigVO 配置对象
     * @param examineRecord           审核记录
     * @param data                    额外数据
     * @return 审核状态
     */
    @Override
    public Integer handleRecordLogByAdvancedConfig(List<ExamineRecordLog> recordLogList, ExamineFlowFinal examineFlowFinal, Boolean init, ExamineAdvancedConfigVO examineAdvancedConfigVO, ExamineRecord examineRecord, Object data) {
        examineRecord = examineRecordService.getById(examineFlowFinal.getRecordId());
        if (ObjectUtil.isNotEmpty(examineAdvancedConfigVO.getLimitTimeStatus()) && examineAdvancedConfigVO.getLimitTimeStatus().equals(1)) {
            examineRecordLimitService.addOrUpdateRecordLimit(examineRecord.getRecordId());
        }

        if (recordLogList == null || recordLogList.isEmpty()) {
            recordLogList = examineRecordService.addExamineRecordLogList(3
                    , examineFlowFinal.getExamineId()
                    , ExamineStatusEnum.PASS.getStatus()
                    , examineFlowFinal.getFlowId()
                    , examineFlowFinal.getRecordId()
                    , 1
                    , "自动审批"
                    , examineFlowFinal.getName()
                    , examineRecord.getTypeId()
                    , PassFlagEnum.PASS_AUTO_NO_USER.getType()
                    , Collections.singletonList(new ExamineFlowFinalUser()));
        }
        LocalDateTime examineTime = recordLogList.stream().findFirst().get().getExamineTime();
        Set<Long> userIdlist = recordLogList.stream()
                .filter(log -> log.getExamineStatus().equals(ExamineStatusEnum.UNDERWAY.getStatus()))
                .map(ExamineRecordLog::getExamineUserId)
                .collect(Collectors.toSet());

        List<Long> normalUserIdList = adminService.queryNormalUserByIds(userIdlist).getData();

        if (!normalUserIdList.isEmpty()) {
            Optional<ExamineRecordLog> recordLogOptional = recordLogList.stream().filter(flow -> normalUserIdList.contains(flow.getExamineUserId())).findFirst();
            if (!recordLogOptional.isPresent()) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
            boolean autoPass = flowCanAutoPass(recordLogOptional.get(), examineFlowFinal, examineAdvancedConfigVO);
            if (autoPass) {
                return examineRecordService.auditExaminePass(recordLogOptional.get(), examineRecord, new UserInfo().setUserId(recordLogOptional.get().getExamineUserId()), ExaminePassBO.builder().dataMap(BeanUtil.beanToMap(data)).init(init).build(), examineTime);
            }
            return null;
        }


        Set<String> collect = recordLogList.stream().filter(log -> log.getExamineStatus().equals(ExamineStatusEnum.UNDERWAY.getStatus()) && StrUtil.isNotEmpty(log.getExamineUserEmail())).map(ExamineRecordLog::getExamineUserEmail).collect(Collectors.toSet());
        if (!collect.isEmpty()) {
            return null;
        }

        //取正在审批的节点
        Optional<ExamineRecordLog> recordLogOptional = recordLogList.stream().filter(log -> log.getExamineStatus().equals(ExamineStatusEnum.UNDERWAY.getStatus())).findFirst();
        if (!recordLogOptional.isPresent()) {
            recordLogOptional = recordLogList.stream().filter(log -> Arrays.asList(ExamineStatusEnum.PASS.getStatus(), ExamineStatusEnum.SKIP.getStatus()).contains(log.getExamineStatus())).findFirst();
            //说明是节点一开始就有通过等特殊场景，查询pass的节点
            if (!recordLogOptional.isPresent()) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
        }
        ExamineRecordLog recordLog = recordLogOptional.get();

        if (ObjectUtil.isNotEmpty(examineAdvancedConfigVO.getNodeHandleType())) {
            if (examineRecord == null) {
                examineRecord = examineRecordService.getById(examineFlowFinal.getRecordId());
            }
            if (examineAdvancedConfigVO.getNodeHandleType().equals(1)) {
                return examineRecordService.auditExaminePass(recordLog, examineRecord, new UserInfo().setUserId(recordLog.getExamineUserId()), ExaminePassBO.builder().init(init).dataMap(BeanUtil.beanToMap(data)).passFlag(PassFlagEnum.PASS_AUTO_NO_VALID_USER.getType()).build(), examineTime);
            }
            if (examineAdvancedConfigVO.getNodeHandleType().equals(2)) {
                return autoForward(examineFlowFinal, examineAdvancedConfigVO.getNodeHandleUser(), examineRecord, recordLog);
            }
        }

        return null;
    }

    /**
     * 自动转交
     *
     * @param examineFlow
     * @param nodeHandleUser
     * @param examineRecord
     * @param curExamineRecordLog
     * @return
     */
    public Integer autoForward(ExamineFlowFinal examineFlow, List<SimpleUser> nodeHandleUser, ExamineRecord examineRecord, ExamineRecordLog curExamineRecordLog) {
        //校验转发有效人员
        List<Long> userIds = nodeHandleUser.stream()
                .map(SimpleUser::getUserId)
                .collect(Collectors.toList());
        List<Long> normalUserIds = adminService.queryNormalUserByIds(userIds).getData();
        List<SimpleUser> normalNodeHandleUser = nodeHandleUser
                .stream()
                .filter(item -> (ObjectUtil.isNotEmpty(item.getOuterUserEmail()) || (ObjectUtil.isNotEmpty(normalUserIds) && normalUserIds.contains(item.getUserId()))))
                .collect(Collectors.toList());
        if (ExamineStatusEnum.COPY.getStatus().equals(curExamineRecordLog.getExamineStatus()) || ExamineStatusEnum.SKIP.getStatus().equals(curExamineRecordLog.getExamineStatus())) {
            return ExamineStatusEnum.PASS.getStatus();
        }
        if (CollectionUtil.isNotEmpty(nodeHandleUser)) {
            //转交指定人
            //异常账户转他人处理默认或签
            examineFlow.setType(3);
            LambdaUpdateWrapper<ExamineFlowFinal> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ExamineFlowFinal::getFlowId, curExamineRecordLog.getFlowId());
            updateWrapper.eq(ExamineFlowFinal::getRecordId, curExamineRecordLog.getRecordId());
            examineFlowFinalService.update(examineFlow, updateWrapper);
            //转交他人处理
            //下一步处理人有值无效，则是员离职等账号异常
            examineRecordLogService.lambdaUpdate()
                    .set(ExamineRecordLog::getExamineStatus, ExamineStatusEnum.FORWARD.getStatus())
                    .set(ExamineRecordLog::getRemarks, "账号异常，自动转交他人处理")
                    .set(ExamineRecordLog::getPassFlag, PassFlagEnum.FORWARD_AUTO_NO_VALID_USER.getType())
                    .eq(ExamineRecordLog::getLogId, curExamineRecordLog.getLogId()).update();
            for (SimpleUser simpleUser : nodeHandleUser) {
                //下一步联系人本身就是为空，则是空部门空角色情况，直接转交他人处理
                //添加日志信息
                ExamineRecordLog examineRecordLog = BeanUtil.copyProperties(curExamineRecordLog, ExamineRecordLog.class);
                examineRecordLog.setExamineId(examineFlow.getExamineId());
                examineRecordLog.setFlowId(examineFlow.getFlowId());
                examineRecordLog.setRecordId(examineFlow.getRecordId());
                examineRecordLog.setBatchId(IdUtil.simpleUUID());
                Long otherUserId = simpleUser.getUserId();
                String otherEmail = simpleUser.getOuterUserEmail();
                examineRecordLog.setLogId(null);
                examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());
                examineRecordLog.setExamineUserId(otherUserId);
                examineRecordLog.setExamineUserEmail(otherEmail);
                examineRecordLog.setCreateTime(curExamineRecordLog.getCreateTime().plusSeconds(1));//其他值不变就修改这几个值
                examineRecordLog.setExamineTime(LocalDateTime.now());
                examineRecordLog.setType(examineFlow.getType());
                examineRecordLog.setPassFlag(null);
                examineRecordLog.setHandlerType(ExamineLogHandlerType.FORWARD.getType());
                examineRecordLog.setRelTarget(curExamineRecordLog.getLogId());
                if (CollectionUtil.isEmpty(normalNodeHandleUser)) {
                    examineRecordLog.setPassFlag(PassFlagEnum.END_AUTO_NO_USER.getType());
                    //设置流程终止
                    examineRecordService.updateExamineRecord(examineFlow.getRecordId(), ExamineStatusEnum.END.getStatus());
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.END.getStatus());
                    // 修改关联模块审核状态
                    ExamineModuleService moduleService = ApplicationContextHolder.getBean(ExamineEnum.parseModule(examineRecord.getLabel()).getServerName());
                    moduleService.updateCheckStatus(examineRecord.getLabel(), examineRecord.getTypeId(), ExamineStatusEnum.END.getStatus(), null);
                    examineRecordLogService.save(examineRecordLog);
                    break;
                } else {
                    if (normalUserIds.contains(simpleUser.getUserId()) || ObjectUtil.isNotEmpty(simpleUser.getOuterUserEmail())) {
                        examineRecordLog.setPassFlag(PassFlagEnum.FORWARD_AUTO_NO_VALID_USER.getType());
                        examineRecordLogService.save(examineRecordLog);
                    }
                }
            }
            //如果是已经转发的记录信息则同意之后不再进行限时处理
            if (ObjectUtil.isEmpty(curExamineRecordLog.getRelTarget())) {
                //添加新增的 现时处理逻辑  插入
                examineRecordLimitService.addOrUpdateRecordLimit(examineFlow.getRecordId());
            }
            if (CollectionUtil.isEmpty(normalNodeHandleUser)) {
                return ExamineStatusEnum.END.getStatus();
            } else {
                return ExamineStatusEnum.UNDERWAY.getStatus();
            }
        } else {
            //设置流程终止
            examineRecordService.updateExamineRecord(examineFlow.getRecordId(), ExamineStatusEnum.END.getStatus());
            //设置审批记录终止
            curExamineRecordLog.setExamineStatus(ExamineStatusEnum.END.getStatus());
            curExamineRecordLog.setPassFlag(PassFlagEnum.END_AUTO_NO_USER.getType());
            examineRecordLogService.updateById(curExamineRecordLog);
            // 修改关联模块审核状态
            ExamineModuleService moduleService = ApplicationContextHolder.getBean(ExamineEnum.parseModule(examineRecord.getLabel()).getServerName());
            moduleService.updateCheckStatus(examineRecord.getLabel(), examineRecord.getTypeId(), ExamineStatusEnum.END.getStatus(), null);
            return ExamineStatusEnum.END.getStatus();
        }

    }


    /**
     * 设置异常配置默认值
     *
     * @param examineAdvancedConfig 审批配置
     * @param isInitLimitTime       是否初始化限时配置
     */
    public ExamineAdvancedConfigVO setDefaultValue(ExamineAdvancedConfig examineAdvancedConfig, boolean isInitLimitTime) {
        ExamineAdvancedConfigVO examineAdvancedConfigVO = BeanUtil.copyProperties(examineAdvancedConfig, ExamineAdvancedConfigVO.class, "nodeHandleUser");

        if (ObjectUtil.isNull(examineAdvancedConfigVO)) {
            examineAdvancedConfigVO = new ExamineAdvancedConfigVO();
        }
        if (ObjectUtil.isNotNull(examineAdvancedConfig)) {
            if (ObjectUtil.isNotNull(examineAdvancedConfig.getNodeHandleUser())) {
                String nodeHandleUser = examineAdvancedConfig.getNodeHandleUser();
                List<Long> userIds = Arrays.stream(nodeHandleUser.split(","))
                        .filter(ObjectUtil::isNotEmpty).map(StrUtil::toString)
                        .filter(NumberUtil::isNumber).map(Long::parseLong).collect(Collectors.toList());
                List<SimpleUser> simpleUsers = new ArrayList<>();
                for (Long userId : userIds) {
                    SimpleUser simpleUser = UserCacheUtil.getSimpleUser(userId);
                    if (ObjectUtil.isNotEmpty(simpleUser)) {
                        simpleUsers.add(simpleUser);
                    }
                }
                examineAdvancedConfigVO.setNodeHandleUser(simpleUsers);
            }
            String modify = examineAdvancedConfig.getModifyPermissionType();
            if (StringUtils.isNotEmpty(modify)) {
                List<Integer> modifyPermissionTypeList = Arrays.stream(modify.split(",")).map(Integer::valueOf).collect(Collectors.toList());
                examineAdvancedConfigVO.setModifyPermissionType(modifyPermissionTypeList);
            }
            if (isInitLimitTime) {
                ExamineAdvancedConfigLimitTime examineAdvancedConfigLimitTime = advancedConfigLimitTimeService.lambdaQuery().eq(ExamineAdvancedConfigLimitTime::getBatchId, examineAdvancedConfig.getBatchId()).one();
                if (ObjectUtil.isNotNull(examineAdvancedConfigLimitTime) && examineAdvancedConfig.getLimitTimeStatus().equals(1)) {
                    ExamineAdvancedConfigLimitTimeVO examineAdvancedConfigLimitTimeVO = new ExamineAdvancedConfigLimitTimeVO();
                    BeanUtil.copyProperties(examineAdvancedConfigLimitTime, examineAdvancedConfigLimitTimeVO);
                    List<ExamineAdvancedConfigLimitTimeUsersVO> handleUserList = advancedConfigLimitTimeUsersService.queryHandleUserList(examineAdvancedConfig.getBatchId());


                    Map<Integer, List<ExamineAdvancedConfigLimitTimeUsersVO>> collect = handleUserList.stream()
                            .collect(Collectors.groupingBy(ExamineAdvancedConfigLimitTimeUsersVO::getType));

                    List<Map<String, Object>> list = new ArrayList<>();
                    collect.forEach((k, v) -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("type", k);
                        map.put("dataList", v);
                        list.add(map);
                    });

                    examineAdvancedConfigLimitTimeVO.setHandleUserList(list);
                    examineAdvancedConfigVO.setAdvancedLimitTimeVO(examineAdvancedConfigLimitTimeVO);
                }
            }
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getNodeHandleType())) {
            examineAdvancedConfigVO.setNodeHandleType(1);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getRepeatHandleType())) {
            examineAdvancedConfigVO.setRepeatHandleType(1);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getRejectHandleType())) {
            examineAdvancedConfigVO.setRejectHandleType(2);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getModifyPermissionType())) {
            examineAdvancedConfigVO.setModifyPermissionType(CollUtil.newArrayList(1, 2));
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getLimitTimeStatus())) {
            examineAdvancedConfigVO.setLimitTimeStatus(0);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getIsTransferable())) {
            examineAdvancedConfigVO.setIsTransferable(true);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getIsConsult())) {
            examineAdvancedConfigVO.setIsConsult(true);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getIsCreateUserWithdraw())) {
            examineAdvancedConfigVO.setIsCreateUserWithdraw(true);
        }
        if (ObjectUtil.isEmpty(examineAdvancedConfigVO.getPrivilege())) {
            examineAdvancedConfigVO.setPrivilege(7);
        }

        return examineAdvancedConfigVO;
    }

    /**
     * 1：查询当前配置的流程是否可以自动通过
     *
     * @param recordLog        当前审核记录
     * @param examineFlowFinal 当前审核流程
     * @param configVO         审核高级配置
     * @return true 可以自动通过 false 不可以自动通过
     */
    private boolean flowCanAutoPass(ExamineRecordLog recordLog, ExamineFlowFinal examineFlowFinal, ExamineAdvancedConfigVO configVO) {
        boolean isAutoPass = false;
        //只有下一层处理人还是当前处理人时才进行推进判断
        if (ObjectUtil.isNotEmpty(configVO)) {
            RepeatHandleTypeEnum repeatHandleTypeEnum = RepeatHandleTypeEnum.valueOf(configVO.getRepeatHandleType());
            if (repeatHandleTypeEnum == null) {
                return false;
            }
            //如果当前流程存在任意一个可编辑的字段，不允许自动通过
            boolean existField = authFieldService.lambdaQuery().eq(ExamineFlowAuthField::getFlowId, examineFlowFinal.getFlowId()).eq(ExamineFlowAuthField::getAuthLevel, 3).exists();
            if (existField) {
                return false;
            }
            switch (repeatHandleTypeEnum) {
                case ONLY_FIRST_NODE:
                case ONLY_SERIES_NODE:
                    //注：sort下标从1开始
                    LambdaQueryChainWrapper<ExamineFlowFinal> chainWrapper = examineFlowFinalService.lambdaQuery().select(ExamineFlowFinal::getFlowId).eq(ExamineFlowFinal::getRecordId, examineFlowFinal.getRecordId());
                    //如果是通过任意一次审核就可，查询sort比之前小的全部审核记录
                    if (repeatHandleTypeEnum == RepeatHandleTypeEnum.ONLY_SERIES_NODE) {
                        //因为存在条件审批的情况，sortId不一定是连续的，所以通过flowId查询
                        chainWrapper.lt(ExamineFlowFinal::getFlowId, examineFlowFinal.getFlowId());
                        chainWrapper.orderByDesc(ExamineFlowFinal::getFlowId);
                        chainWrapper.last("limit 1");
                    }
                    List<Long> preExamineFlowFinal = chainWrapper.list().stream().map(ExamineFlowFinal::getFlowId).collect(Collectors.toList());
                    if (preExamineFlowFinal.isEmpty()) {
                        return false;
                    }
                    Integer count = examineRecordLogService.lambdaQuery()
                            .eq(ExamineRecordLog::getRecordId, examineFlowFinal.getRecordId())
                            .in(ExamineRecordLog::getFlowId, preExamineFlowFinal)
                            .and(wrapper -> {
                                wrapper.or(newWrapper -> {
                                    newWrapper.eq(ExamineRecordLog::getExamineUserId, recordLog.getExamineUserId());
                                });
                                wrapper.or(newWrapper -> {
                                    newWrapper.eq(ExamineRecordLog::getExamineUserEmail, recordLog.getExamineUserEmail());
                                });
                            })
                            .eq(ExamineRecordLog::getExamineStatus, ExamineStatusEnum.PASS.getStatus())
                            .count().intValue();
                    if (count >= 1) {
                        isAutoPass = true;
                    }
                    break;
                default:
                    break;
            }
        }
        return isAutoPass;
    }

}
